import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
import request from '/@/utils/request';
import { BaseRegionCode } from '/@/config/geoserver';
import { Session } from '/@/utils/storage';
import { validateNull } from '/@/utils/validate';
import { useMessageBox } from '../hooks/message';
import router from '/@/router';
import { Base64 } from 'js-base64';
import { regionList } from '/@/api/common';

/**
 * 获取用户geoserver权限
 * @returns
 */
export function getUserAuthKey(layerName: any) {
	const stores = useUserInfo();
	const { userInfos } = storeToRefs(stores);
	let userInfo = userInfos.value.user;
	if (userInfo) {
		let authkey = userInfo.readGisKey || userInfo.gisKey ? `${layerName},${userInfo.readGisKey || userInfo.gisKey},${userInfo.tenantId}` : '';
		return authkey;
	}
}

/**
 * 异步加载村镇通用方法
 * @param {Number} length
 * @returns
 */
export function lazyLoadRegionList(length = 1, defaultValue = BaseRegionCode.value) {
	return async (node: { level: any; value: any }, resolve: (arg0: any) => void) => {
		const { level, value } = node;
		let list = [];
		let data = await regionList(value || defaultValue);
		if (data.code == 0) {
			list = data.data.map((el: { regionName: any; regionCode: any }) => {
				return { label: el.regionName, value: el.regionCode };
			});
		}
		const nodes = list.map((item: any) => Object.assign(item, { leaf: level >= length }));
		// 通过调用resolve将子节点数据返回，通知组件数据加载完成
		resolve(nodes);
	};
}

/**
 * 计算数字的加减法
 * @param {*} numMax
 * @param {*} numMin
 * @param {*} type  1 加法  2 减法  3 除法  4 乘法
 * @returns
 */
export function computeNumberAddOrMinus(numMax = 0, numMin = 0, type = 1) {
	const regex = /^\d+(\.\d+)?$/;
	if (!regex.test(numMax.toString())) {
		console.log('第一个参数非数字');
		return 0;
	}
	if (!regex.test(numMin.toString())) {
		console.log('第二个参数非数字');
		return 0;
	}
	if (type == 4) {
		if (numMin == 0) {
			console.log('第二个参数不能为零');
			return 0;
		}
	}
	let max_int = parseInt(numMax.toString());
	let min_int = parseInt(numMin.toString());
	let max_dec = numMax.toString().split('.')[1] || '';
	let min_dec = numMin.toString().split('.')[1] || '';
	let max_dec_lth = max_dec.length;
	let min_dex_lth = min_dec.length;
	let max_lth = max_dec_lth > min_dex_lth ? max_dec_lth : min_dex_lth;
	if (type == 1) {
		//加法
		let result_int = max_int + min_int;
		let result_dec = Number(max_dec) * Math.pow(10, max_lth - max_dec_lth) + Number(min_dec) * Math.pow(10, max_lth - min_dex_lth);
		return (result_int * Math.pow(10, max_lth) + result_dec) / Math.pow(10, max_lth);
	} else if (type == 2) {
		//减法
		let result_int = max_int - min_int;
		let result_dec = Number(max_dec) * Math.pow(10, max_lth - max_dec_lth) - Number(min_dec) * Math.pow(10, max_lth - min_dex_lth);
		return (result_int * Math.pow(10, max_lth) + result_dec) / Math.pow(10, max_lth);
	} else if (type == 3) {
		let result = (numMax * Math.pow(10, max_dec_lth) * (numMin * Math.pow(10, min_dex_lth))) / Math.pow(10, max_dec_lth + min_dex_lth);
		return result;
	} else if (type == 4) {
		let result = (numMax * Math.pow(10, max_lth)) / (numMin * Math.pow(10, max_lth));
		return result;
	}
}

// 手机号脱敏
export function maskPhoneNumber(phoneNumber: string) {
	return phoneNumber ? phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '';
}

/**
 * 判断是否登录 true 已登录  false 未登录
 * @param redirect 登录成功后跳转地址
 * @returns
 */
export function checkUserLogin(redirect: String) {
	let token = Session.getToken();
	if (validateNull(token)) {
		if (!validateNull(redirect)) {
			Session.set('login_redirect_url', redirect);
		} else {
			Session.remove('login_redirect_url');
		}
		useMessageBox()
			.confirm('本功能需要登录使用，点击“确认”按钮跳转到登录页面')
			.then((res) => {
				router.push('/');
			});
		return false;
	} else {
		return true;
	}
}

/**
 *
 * @param {String} imgLink 图片URL
 * @param {String} scale 缩放比例
 * @returns {String}
 */
export function thumbnail(imgLink: string, scale = '100x100') {
	let reg = new RegExp('(http(s)?://.+?(/files)?/)(.*)');

	if (!reg.test(imgLink)) return imgLink;

	let url = imgLink.replace(reg, ($1, $2, $3, $4, $5) => {
		return $2 + (scale + '/') + $5;
	});
	return url;
}

/**
 * 获取媒体数据签名
 * @param code
 * @returns
 */
export function getFileSign(code: String) {
	let token = Session.getToken();
	let tenantId = Session.getTenant();
	let sign = Base64.encode(`${tenantId},${code},${token}`);
	return `?sign=${sign}`;
}

// 获取字典映射
export function getDictMap(dicArr: any) {
	if (isRef(dicArr)) {
		dicArr = unref(dicArr);
	}
	return Object.fromEntries((dicArr || []).map((d:any) => [d.value, d.label]));
}
